package demo1.mapper;

import demo1.dbutil.DBUtil;
import demo1.dbutil.IDBUtil;
import demo1.userinfo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Component
public class UserMapper implements IUserMapper {
    @Autowired
    private IDBUtil dbUtil;

    public int insert(UserInfo userInfo) {
        try (Connection connection = dbUtil.getConnection()) {
            String sql = "INSERT INTO userinfo(username,password,nickname,age) VALUES(?,?,?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, userInfo.getUsername());
            ps.setString(2, userInfo.getPassword());
            ps.setString(3, userInfo.getNickname());
            ps.setInt(4, userInfo.getAge());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public boolean query(UserInfo userInfo) {
        try (Connection connection = dbUtil.getConnection()) {
            String sql = "SELECT username,password,nickname,age FROM userinfo WHERE username = ? AND password = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, userInfo.getUsername());
            ps.setString(2, userInfo.getPassword());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                userInfo.setNickname(rs.getString("nickname"));
                userInfo.setAge(rs.getInt("age"));
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
